/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_adapter/cooling.h"

namespace dev {

bool NetworkAdapter_Cooling::update_chip_temp_by_ncsi() {
    ncsi_temp_info_t chip_info = {};
    bool     ret =
        m_ncsi_over_mctp_mellanox->get_temp_info(m_package_id, DEFAULT_CHANNEL_ID, 0, &chip_info);
    if (!ret) {
        ilog("Error: Failed to update chip temp");
        return false;
    }
    TemperatureCelsius.set_value(static_cast<int16_t>(chip_info.cur_temp));
    TemperatureStatus.set_value(static_cast<uint16_t>(chip_info.cur_temp) < CHIP_TEMP_INVALID ? 0 : 1);
    return true;
}

bool NetworkAdapter_Cooling::update_max_sfp_temperature(uint16_t max_temperature, uint8_t status) {
    MaxSFPTemperatureCelsius.set_value(max_temperature);
    MaxSFPTemperatureStatus.set_value(status);
    return true;
}

void NetworkAdapter_Cooling::start_ncsi_update_task_mellanox(ncsi_over_mctp_mellanox_ptr ncsi_over_mctp,
                                                           mc::milliseconds      interval,
                                                            uint8_t               package_id) {
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_over_mctp_mellanox = ncsi_over_mctp;
    m_package_id = package_id;
    m_ncsi_timer->timeout.connect([this]() {
        update_chip_temp_by_ncsi();
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkAdapter_Cooling::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
    }
    if (m_ncsi_over_mctp_mellanox) {
        m_ncsi_over_mctp_mellanox = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkAdapter_Cooling)